﻿using System;
using System.Diagnostics;
using System.Threading;

namespace BaseSyntax.ThreadTest
{
	public class ThreadErrorCatcher:ITest
	{
		public static Stopwatch clock = new Stopwatch();
		
		public void Test()
		{
			ManualResetEventSlim resetEvent = new ManualResetEventSlim();
			try
			{
				clock.Start();

				AppDomain.CurrentDomain.UnhandledException +=
				(s, e) =>
				{
					Message("Event handler starting");
					Delay(4000);
				};
				
				Thread thread = new Thread(() =>
				{
					Message("Throwing exception.");
					throw new Exception();
				});
				thread.Start();
				
				// 此打印会优先于thread里面的内容
				Message("after thread start");
				
				if (!resetEvent.Wait(6000))
				{
					Message("Timed out waiting for unhandled exception.");
				}
			}
			finally
			{
				Message("Finally block running.");
			}
		}
		
		static void Delay(int i)
		{
			Message($"Sleeping for {i} ms");
			Thread.Sleep(i);
			Message("Awake");
		}

		static void Message(string text)
		{
			Console.WriteLine(
				$"{Thread.CurrentThread.ManagedThreadId}:{text}, {DateTime.Now}");
		}
	}
}